package com.example.rule.util;

import com.example.rule.constant.RuleConstant;
import com.example.rule.core.Rule;
import com.example.rule.db.entity.PymtRule;
import com.example.rule.db.repository.PymtRuleRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.util.Collections;
import java.util.List;

/**
 * @author Jason - Chusifeng
 * @version 1.0.0
 * @className CacheLoader.java
 * @packageName com.example.rule.util
 * @createTime 2022年10月10日 10:25:19
 * @description 加载本次缓存的数据
 */

@Slf4j
public class CacheLoader extends com.google.common.cache.CacheLoader<String, List<Rule>> {

    private PymtRuleRepository ruleRepository;

    @Override
    public List<Rule> load(String key) throws Exception {
        if (ruleRepository == null) {
            ruleRepository = SpringApplicationUtils.getApplicationContext().getBean(PymtRuleRepository.class);
        }
        if (RuleConstant.RULE_CACHE_KEY.equals(key)) {
            List<Rule> ruleList = CacheUtil.getRules();
            if (CollectionUtils.isEmpty(ruleList)) {
                List<PymtRule> pymtRules = ruleRepository.findAll();
                CacheUtil.cacheRule(pymtRules);
                return CacheUtil.getRules();
            }
        }
        return Collections.emptyList();
    }

}
